import { Application } from "egg";
import CodoBase from "../../CodoBase";
import CodoError from "../../CodoError";

export default class HCMqttBaseService extends CodoBase {
	constructor(public topic: string, protected app: Application) {
		super(app);
	}

	private mqttClient: IMQTTClient;
	/** 获取ehrnode server的mqtt客户端实例 */
	getMQTTClient() {
		if (this.mqttClient) return this.mqttClient;
		const mqtt = this.dataManager.provider?.HCMQTTClient; //使用此特殊标识从外部获取mqtt客户端
		if (!mqtt) throw new CodoError("data manager not provide hc.mqtt.client");
		this.mqttClient = mqtt;
		return mqtt;
	}
}

/** mqtt client实例的接口 */
export interface IMQTTClient {
	/** 请求mqtt，并通过messageId响应 */
	fetch<T>(
		topic: string,
		data: any,
		options?: Record<string, any>,
		timeout?: number
	): Promise<{ message: T }>;
}
